<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            height: 5000px;
        }
        
        #btn {
            position: fixed;
            bottom: 100px;
            right: 100px;
            display: none;
        }
    </style>
</head>

<body>
    <button id="btn">点击回到顶部</button>
    <script>
        window.onscroll = function() {
            if (scrollY >= 2000) {
                btn.style.display = 'block'
            } else {
                btn.style.display = 'none'
            }
        }
        var time;
        // 绑定点击事件
        btn.onclick = function() {
            // 添加定时器用个变量来接
            clearInterval(time)
            var time = setInterval(function() {
                // 设置条件到顶部的时候清除定时器·
                if (scrollY <= 0) {
                    clearInterval(time)
                }
                // 给滚动条每次减100不然会直接滚到上面不然没有动画
                scrollTo({
                    top: scrollY - 100
                });
            }, 100);

        }
    </script>
</body>

</html>